﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Linq;
using Microsoft.IdentityModel.Protocols.WSFederation;
using Microsoft.IdentityModel.Web;
using Microsoft.SharePoint.ApplicationPages;

namespace Veracruz.Facebook.Sharepoint.FeatureActions
{
    public partial class FacebookAuth 
        :GlobalAdminPageBase
        //: WebAdminPageBase
    {
        public const string CachedClaims = "CachedClaims";
        //public const string RedirectionTarget = "applications.aspx";

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ProcessRequest();
        }

        protected override void OnLoad(System.EventArgs e)
        {
            
            //ProcessRequest();
            base.OnLoad(e);
        }
        public void ProcessRequest()
        {
            //WSFederationAuthenticationModule l_federatedAuthenticationModule = null;// WSFederationAuthenticationModule.Current;
            WSFederationAuthenticationModule l_federatedAuthenticationModule = this.Context.ApplicationInstance.Modules.OfType<WSFederationAuthenticationModule>().FirstOrDefault();

            //HACK
            if (!this.Context.Request.IsAuthenticated && l_federatedAuthenticationModule != null)
            {
                string l_returnUrl = l_federatedAuthenticationModule.GetReturnUrlFromResponse(this.Context.Request);
                //if (!l_federatedAuthenticationModule.IsPassiveSignInResponse(context.Request))
                if (l_federatedAuthenticationModule.PassiveRedirectEnabled == false)
                {
                    // User is trying to get to the page w/o being authenticated
                    // We are going to redirect him to our STS. The address is stored in FAM.Issuer property
                    //l_federatedAuthenticationModule.RedirectToIdentityProvider(context);
                    l_federatedAuthenticationModule.RedirectToIdentityProvider(Guid.NewGuid().ToString(), l_returnUrl);
                }
                else
                {
                    //
                    // We have a WS-Federation Passive Protocol SignIn Response message from the STS. 
                    // Extract the token and attempt to sign-in the user
                    //

                    // Get the xml token from the form post
                    //string l_tokenXml = l_federatedAuthenticationModule.GetXmlTokenFromPassiveSignInResponse(context.Request, null);

                    //if (String.IsNullOrEmpty(l_tokenXml))
                    //{
                    //    throw new InvalidOperationException("Cannot parse the returned security token");
                    //}

                    //// Validate the token
                    //SecurityToken token = null;
                    //IClaimsPrincipal l_principal = l_federatedAuthenticationModule.AuthenticateUser(l_tokenXml, out token);
                    //SecurityToken token = l_federatedAuthenticationModule.GetSecurityToken(context.Request);

                    //// store the token in the session for later use
                    //if (context.Session == null)
                    //{
                    //    throw new Exception("No session available to save the token");
                    //}
                    //context.Session[CachedToken] = token;

                    //// Perform Signin. 
                    //string l_signOutUrl = GetPathAndQuery(new SignOutRequestMessage(new Uri(l_federatedAuthenticationModule.Issuer)));

                    //// The second param in SignInParameters.ctor denotes whether a persistent cookie is issued or not. 
                    //l_federatedAuthenticationModule.IssueTicket(new TicketGenerationContext(l_principal, false, l_signOutUrl, GetType().Name));

                    String l_tokenXml = String.Empty;

                    Microsoft.IdentityModel.Tokens.SessionSecurityToken l_token = l_federatedAuthenticationModule.GetSecurityToken(this.Context.Request) as Microsoft.IdentityModel.Tokens.SessionSecurityToken;
                    l_federatedAuthenticationModule.SetPrincipalAndWriteSessionToken(l_token, true);
                    //l_federatedAuthenticationModule.SignIn(l_tokenXml);
                    if (String.IsNullOrEmpty(l_returnUrl))
                    {
                        this.Context.Response.Redirect("~/", true);
                    }
                    else
                    {
                        this.Context.Response.Redirect(l_returnUrl, true);
                    }

                }
            }
        }

        //public void ProcessRequest()
        //{
        //    FederatedAuthenticationModule l_federatedAuthenticationModule = FederatedAuthenticationModule.Current;

        //    if (l_federatedAuthenticationModule == null)
        //    {
        //        throw new ConfigurationErrorsException("FederatedAuthenticationModule not found.");
        //    }
            
        //    //HACK: No session available by default so don't forget to activate it 
        //    //in web.config (module Session and EnableSessionState = true)
        //    if(this.Context.Session[CachedClaims] == null)
        //    {
        //        if (!l_federatedAuthenticationModule.IsPassiveSignInResponse(this.Context.Request))
        //        {
        //            // User is trying to get to the page w/o being authenticated
        //            // We are going to redirect him to our STS. The address is stored in FAM.Issuer property
        //            l_federatedAuthenticationModule.RedirectToIdentityProvider(this.Context);
        //        }
        //        else
        //        {
        //            // Get the xml token from the form post
        //            string l_tokenXml = l_federatedAuthenticationModule.GetXmlTokenFromPassiveSignInResponse(this.Context.Request, null);

        //            if (String.IsNullOrEmpty(l_tokenXml))
        //            {
        //                throw new InvalidOperationException("Cannot parse the returned security token");
        //            }

        //            // Validate the token
        //            SecurityToken token = null;
        //            IClaimsPrincipal l_principal = l_federatedAuthenticationModule.AuthenticateUser(l_tokenXml, out token);

        //            //HACK: No session available by default so don't forget to activate it 
        //            //in web.config (module Session and EnableSessionState = true)
        //             this.Context.Session[CachedClaims] = l_principal;

        //            //_admin/applications.aspx
        //            //SPUtility.Redirect("applications.aspx", SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
        //             //SPUtility.Redirect("/_admin/applications.aspx", SPRedirectFlags.Static, this.Context);
        //             RedirectToApplicationManagementPage();
        //        }
        //    }
        //}

        private static string GetPathAndQuery(WSFederationMessage request)
        {
            StringBuilder l_strb = new StringBuilder(128);
            using (StringWriter writer = new StringWriter(l_strb, CultureInfo.InvariantCulture))
            {
                request.Write(writer);
                return l_strb.ToString();
            }
        }
    }
}
